import { prisma } from '../../../utils/prisma'
import { getUserIdOrThrow } from '../../../utils/guard'
import { z } from 'zod'

const bodySchema = z.object({
  title: z.string().min(1).optional(),
  pointsPerUnit: z.number().int().optional(),
  allowQuantity: z.boolean().optional(),
  unitLabel: z.string().optional(),
  isArchived: z.boolean().optional()
})

export default eventHandler(async (event) => {
  const userId = getUserIdOrThrow(event)
  const id = Number(getRouterParam(event, 'id'))
  if (!Number.isFinite(id)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  const body = await readBody(event)
  const parsed = bodySchema.safeParse(body)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })

  const exists = await prisma.activityTemplate.findFirst({ where: { id, userId } })
  if (!exists) throw createError({ statusCode: 404, statusMessage: 'NOT_FOUND' })
  const template = await prisma.activityTemplate.update({
    where: { id },
    data: parsed.data
  })
  return { template }
})


